// utils/mockData.js
// 模拟数据，用于在没有后端API时进行测试

// Helper to generate iOS-compatible date strings
function getMockDate() {
  const d = new Date();
  const year = d.getFullYear();
  const month = (d.getMonth() + 1).toString().padStart(2, '0');
  const day = d.getDate().toString().padStart(2, '0');
  const hour = d.getHours().toString().padStart(2, '0');
  const minute = d.getMinutes().toString().padStart(2, '0');
  const second = d.getSeconds().toString().padStart(2, '0');
  return `${year}/${month}/${day} ${hour}:${minute}:${second}`;
}

// 模拟律师数据
const mockLawyers = [
  {
    id: '1001',
    lawyerId: '1001',
    name: '罗槟',
    title: '执业律师',
    avatar: '/static/images/avatar/罗槟.jpg',
    location: '江西省 南昌市',
    specialty: '民事、合同、公司改制',
    years: '4',
    consultCount: '1024',
    rating: 5,
    phone: '13866666666',
    lawFirm: '权璟律师事务所',
    licenseNumber: 'LAW123456'
  },
  {
    id: '1002',
    lawyerId: '1002',
    name: '何赛',
    title: '高级合伙人',
    avatar: '/static/images/avatar/何赛.jpg',
    location: '江西省 南昌市',
    specialty: '经济、民事、合同',
    years: '6',
    consultCount: '856',
    rating: 4,
    phone: '13888888888',
    lawFirm: '权璟律师事务所',
    licenseNumber: 'LAW123457'
  },
  {
    id: '1003',
    lawyerId: '1003',
    name: '顾婕',
    title: '创始合伙人',
    avatar: '/static/images/avatar/顾婕.jpg',
    location: '江西省 南昌市',
    specialty: '民事、合同、房地产、婚姻继承',
    years: '8',
    consultCount: '1200',
    rating: 5,
    phone: '13855555555',
    lawFirm: '权璟律师事务所',
    licenseNumber: 'LAW123458'
  },
  {
    id: '1004',
    lawyerId: '1004',
    name: '封印',
    title: '创始人',
    avatar: '/static/images/avatar/封印.jpg',
    location: '江西省 南昌市',
    specialty: '风险防范、纠纷化解、权益维护',
    years: '10',
    consultCount: '1500',
    rating: 5,
    phone: '13877777777',
    lawFirm: '权璟律师事务所',
    licenseNumber: 'LAW123459'
  }
];

// 模拟收藏数据
let mockFavorites = [
  {
    id: '1',
    lawyerId: '1001',
    userId: 'user123',
    createTime: '2024/01/15 10:30:00'
  },
  {
    id: '2',
    lawyerId: '1003',
    userId: 'user123',
    createTime: '2024/01/16 14:20:00'
  }
];

const mockOrders = [
  {
    orderId: 'order1001',
    lawyerId: '1001',
    lawyerName: '罗槟',
    serviceType: '电话咨询',
    price: 100,
    status: '待付款',
    createTime: '2024/06/01 10:00:00',
    detail: '电话咨询服务',
    paymentType: '',
    comment: null,
    unreadCount: 1
  },
  {
    orderId: 'order1002',
    lawyerId: '1002',
    lawyerName: '何赛',
    serviceType: '图文咨询',
    price: 200,
    status: '已完成',
    createTime: '2024/06/02 11:00:00',
    detail: '图文咨询服务',
    paymentType: '微信',
    comment: { content: '服务很好', rating: 5 }
  }
];

let orderIdSeed = 1003;

// 模拟聊天消息数据
const mockChatMessages = {
  'order1001': [
    {
      role: 'user',
      content: '您好，罗律师，我是张角，想咨询一下关于合同纠纷的问题',
      createTime: '2024/06/10 10:30:00',
    },
    {
      role: 'lawyer',
      content: '您好张先生，我是罗槟，很高兴为您服务。请详细说明一下您的合同纠纷情况。',
      createTime: '2024/06/10 10:31:00',
    }
  ],
  'order1002': [
    {
      role: 'user',
      content: '何律师您好，我是张角，想咨询一下关于劳动纠纷的问题',
      createTime: '2024/06/11 14:20:00',
    },
    {
      role: 'lawyer',
      content: '您好张先生，我是何赛，很高兴为您服务。请详细说明一下您的劳动纠纷情况。',
      createTime: '2024/06/11 14:21:00',
    }
  ]
};

let mockComments = [
  {
    commentId: 'comment001',
    orderId: 'order1002',
    lawyerId: '1002',
    userId: 'user123',
    userName: '张角',
    userAvatar: 'https://ossweb-img.qq.com/images/lol/web201310/skin/big107000.jpg',
    content: '何律师非常专业，解答问题很耐心，帮我解决了一个大难题！',
    rating: 5,
    createTime: '2024/06/03 10:00:00',
    reply: {
      content: '感谢您的认可，能帮到您是我的荣幸。',
      createTime: '2024/06/03 11:00:00'
    }
  },
  {
    commentId: 'comment002',
    orderId: 'order_completed_with_luobin', // Assume this is a completed order for Luo Bin
    lawyerId: '1001',
    userId: 'user456',
    userName: '匿名用户',
    userAvatar: 'https://ossweb-img.qq.com/images/lol/web201310/skin/big10001.jpg',
    content: '服务态度很好，虽然问题还没完全解决，但律师很负责。',
    rating: 4,
    createTime: '2024/06/05 15:30:00',
    reply: null
  }
];

// 模拟API响应
const mockAPI = {
  // 获取收藏列表
  getFavoriteList: (pageNum, pageSize) => {
    return new Promise((resolve) => {
      setTimeout(() => {
        const start = (pageNum - 1) * pageSize;
        const end = start + pageSize;
        const list = mockFavorites.slice(start, end).map(favorite => {
          const lawyer = mockLawyers.find(l => l.lawyerId === favorite.lawyerId);
          return {
            ...lawyer,
            favoriteId: favorite.id,
            createTime: favorite.createTime
          };
        });
        
        resolve({
          code: 200,
          msg: 'success',
          data: {
            list: list,
            total: mockFavorites.length,
            pageNum: pageNum,
            pageSize: pageSize
          }
        });
      }, 500); // 模拟网络延迟
    });
  },

  // 添加收藏
  addFavorite: (lawyerId) => {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        // 检查是否已经收藏
        const existing = mockFavorites.find(f => f.lawyerId === lawyerId);
        if (existing) {
          reject(new Error('该律师已收藏'));
          return;
        }

        // 添加收藏
        const newFavorite = {
          id: Date.now().toString(),
          lawyerId: lawyerId,
          userId: 'user123',
          createTime: getMockDate()
        };
        mockFavorites.push(newFavorite);

        resolve({
          code: 200,
          msg: '收藏成功',
          data: newFavorite
        });
      }, 300);
    });
  },

  // 取消收藏
  cancelFavorite: (lawyerId) => {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        const index = mockFavorites.findIndex(f => f.lawyerId === lawyerId);
        if (index === -1) {
          reject(new Error('未找到收藏记录'));
          return;
        }

        mockFavorites.splice(index, 1);

        resolve({
          code: 200,
          msg: '取消收藏成功',
          data: null
        });
      }, 300);
    });
  },

  // 检查收藏状态
  checkFavoriteStatus: (lawyerId) => {
    return new Promise((resolve) => {
      setTimeout(() => {
        const isFavorited = mockFavorites.some(f => f.lawyerId === lawyerId);
        resolve({
          code: 200,
          msg: 'success',
          data: {
            isFavorited: isFavorited
          }
        });
      }, 200);
    });
  },

  // 创建订单
  createOrder: ({ lawyerId, serviceType, price }) => {
    return new Promise((resolve) => {
      setTimeout(() => {
        const lawyer = mockLawyers.find(l => l.lawyerId === lawyerId);
        const newOrder = {
          orderId: 'order' + orderIdSeed++,
          lawyerId,
          lawyerName: lawyer ? lawyer.name : '模拟律师',
          serviceType,
          price,
          status: '待付款',
          createTime: getMockDate(),
          detail: serviceType + '服务',
          paymentType: '',
          comment: null
        };
        mockOrders.unshift(newOrder);
        resolve({ code: 200, msg: '创建成功', data: newOrder });
      }, 300);
    });
  },

  // 订单列表
  getOrderList: ({ status, pageNum = 1, pageSize = 10 }) => {
    return new Promise((resolve) => {
      setTimeout(() => {
        let list = mockOrders;
        if (status) list = list.filter(o => o.status === status);
        const start = (pageNum - 1) * pageSize;
        const end = start + pageSize;
        resolve({
          code: 200,
          msg: 'success',
          data: {
            list: list.slice(start, end),
            total: list.length,
            pageNum,
            pageSize
          }
        });
      }, 300);
    });
  },

  // 订单详情
  getOrderDetail: (orderId) => {
    return new Promise((resolve) => {
      setTimeout(() => {
        const order = mockOrders.find(o => o.orderId === orderId);
        resolve({ code: 200, msg: 'success', data: order });
      }, 200);
    });
  },

  // 取消订单
  cancelOrder: (orderId) => {
    return new Promise((resolve) => {
      setTimeout(() => {
        const order = mockOrders.find(o => o.orderId === orderId);
        if (order) order.status = '已取消';
        resolve({ code: 200, msg: '已取消', data: null });
      }, 200);
    });
  },

  // 支付订单
  payOrder: ({ orderId, paymentType }) => {
    return new Promise((resolve) => {
      setTimeout(() => {
        const order = mockOrders.find(o => o.orderId === orderId);
        if (order) {
          order.status = '待服务';
          order.paymentType = paymentType;
        }
        resolve({ code: 200, msg: '支付成功', data: null });
      }, 300);
    });
  },

  // 完成订单
  completeOrder: (orderId) => {
    return new Promise((resolve) => {
      setTimeout(() => {
        const order = mockOrders.find(o => o.orderId === orderId);
        if (order) order.status = '已完成';
        resolve({ code: 200, msg: '已完成', data: null });
      }, 200);
    });
  },

  // 订单评价
  commentOrder: ({ orderId, content, rating }) => {
    return new Promise((resolve) => {
      setTimeout(() => {
        const order = mockOrders.find(o => o.orderId === orderId);
        if (order) {
          const newComment = {
            commentId: 'comment' + Date.now(),
            orderId: orderId,
            lawyerId: order.lawyerId,
            userId: 'currentUser', // Assume current user
            userName: '张角',
            userAvatar: 'https://ossweb-img.qq.com/images/lol/web201310/skin/big107000.jpg',
            content,
            rating,
            createTime: getMockDate(),
            reply: null
          };
          mockComments.push(newComment);
          order.comment = { content, rating };
        }
        resolve({ code: 200, msg: '评价成功', data: null });
      }, 200);
    });
  },

  // 获取评论列表
  getCommentList: ({ lawyerId, sort = 'newest' }) => {
    return new Promise((resolve) => {
      setTimeout(() => {
        let list = mockComments.filter(c => c.lawyerId === lawyerId);
        if (sort === 'newest') {
          list.sort((a,b) => new Date(b.createTime) - new Date(a.createTime));
        } else if (sort === 'rating') {
          list.sort((a,b) => b.rating - a.rating);
        }
        resolve({
          code: 200,
          msg: 'success',
          data: {
            list: list,
            total: list.length
          }
        });
      }, 200);
    });
  },

  // 回复评论
  replyToComment: ({ commentId, content }) => {
    return new Promise((resolve) => {
      setTimeout(() => {
        const comment = mockComments.find(c => c.commentId === commentId);
        if (comment) {
          comment.reply = {
            content,
            createTime: getMockDate()
          };
        }
        resolve({ code: 200, msg: '回复成功', data: null });
      }, 200);
    });
  },

  // 获取聊天历史
  getChatHistory: (orderId) => {
    return new Promise((resolve) => {
      setTimeout(() => {
        const messages = mockChatMessages[orderId] || [];
        resolve({
          code: 200,
          msg: 'success',
          data: {
            list: messages,
            total: messages.length
          }
        });
      }, 200);
    });
  },

  // 获取所有消息列表，用于会话列表页
  getMessageList: (pageNum, pageSize) => {
    return new Promise((resolve) => {
      setTimeout(() => {
        let allMessages = [];
        Object.keys(mockChatMessages).forEach(orderId => {
          const order = mockOrders.find(o => o.orderId === orderId);
          const lawyer = mockLawyers.find(l => l.lawyerId === order.lawyerId);

          mockChatMessages[orderId].forEach(msg => {
            allMessages.push({
              ...msg,
              orderId: orderId,
              lawyerName: order ? order.lawyerName : '未知律师',
              lawyerAvatar: lawyer ? lawyer.avatar : '',
              unreadCount: order ? order.unreadCount || 0 : 0
            });
          });
        });
        
        allMessages.sort((a, b) => new Date(b.createTime) - new Date(a.createTime));
        
        const start = (pageNum - 1) * pageSize;
        const end = start + pageSize;
        const paginatedMessages = allMessages.slice(start, end);

        resolve({
          code: 200,
          msg: 'success',
          data: {
            list: paginatedMessages,
            total: allMessages.length
          }
        });
      }, 200);
    });
  },

  // 标记消息为已读
  readMessages: (orderId) => {
    return new Promise((resolve) => {
      setTimeout(() => {
        const order = mockOrders.find(o => o.orderId === orderId);
        if (order) {
          order.unreadCount = 0; // Directly set the count to 0
        }
        console.log(`Mock: Marked messages for order ${orderId} as read.`);
        resolve({ code: 200, msg: 'success' });
      }, 100);
    });
  },

  // 发送消息
  sendMessage: ({ orderId, content, role = 'user' }) => {
    return new Promise((resolve) => {
      setTimeout(() => {
        const newMessage = {
          role: role,
          content: content,
          createTime: getMockDate(),
        };

        if (!mockChatMessages[orderId]) {
          mockChatMessages[orderId] = [];
        }
        mockChatMessages[orderId].push(newMessage);

        resolve({
          code: 200,
          msg: '发送成功',
          data: newMessage
        });
      }, 200);
    });
  }
};

module.exports = {
  mockLawyers,
  mockFavorites,
  mockOrders,
  mockChatMessages,
  mockAPI
}; 